import 'package:animated_transitions/animated_transitions.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:vamos/view/system/auth_page.dart';
import 'package:zo_animated_border/zo_animated_border.dart';
import '../../core/index.dart';
import '../../core/widgets/toast_notifications.dart';
import '../../core/widgets/report_dialog.dart';
import '../../core/widgets/follow_user_dialog.dart';
import 'video_call_page.dart';

/// 聊天界面
class VamosChatInterface extends StatefulWidget {
  const VamosChatInterface({super.key});

  @override
  State<VamosChatInterface> createState() => _VamosChatInterfaceState();
}

class _VamosChatInterfaceState extends State<VamosChatInterface>
    with RouteAware {
  String? _selectedConversationId;

  @override
  Widget build(BuildContext context) {
    return StoreConnector<AppState, AppState>(
      converter: (store) => store.state,
      builder: (context, state) {
        // 监听Redux状态中的活动对话变化
        final activeConversationId = state.chatState.activeConversationId;
        if (activeConversationId != null &&
            activeConversationId != _selectedConversationId) {
          WidgetsBinding.instance.addPostFrameCallback((_) {
            setState(() {
              _selectedConversationId = activeConversationId;
            });
          });
        }

        return Scaffold(
          body: Container(
            width: double.infinity,
            height: double.infinity,
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/my_background.png'),
                fit: BoxFit.cover,
              ),
            ),
            child: _buildChatContent(state),
          ).safeArea(top: false, bottom: false),
        );
      },
    );
  }

  Widget _buildChatContent(AppState state) {
    final currentUser = state.userState.activeUser;

    if (currentUser == null) {
      return _buildLoginPrompt();
    }

    return _buildChatInterface(state);
  }

  Widget _buildLoginPrompt() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        // 项目Logo
        Container(
          width: 120.w,
          height: 120.w,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(34.r),
            image: const DecorationImage(
              image: AssetImage('assets/images/logo.png'),
              fit: BoxFit.cover,
            ),
          ),
        ).paddingBottom(32.h),

        // 提示信息
        Text(
          'Please login to access chat features',
          style: TextStyle(
            color: Colors.white,
            fontSize: 18.sp,
            fontWeight: FontWeight.w500,
          ),
          textAlign: TextAlign.center,
        ).paddingHorizontal(32.w).paddingBottom(24.h),

        // 前往登录按钮
        ZoAnimatedGradientBorder(
          borderRadius: 24.r,
          borderThickness: 2.0,
          animationDuration: Durations.extralong4,
          gradientColor: const [
            Color(0xFF83BE4A),
            Color(0xFFF3E3C6),
            Color(0xFFFB894E),
          ],
          child: Container(
            width: 200.w,
            height: 48.h,
            decoration: BoxDecoration(
              gradient: const LinearGradient(
                colors: [
                  Color(0xFF83BE4A),
                  Color(0xFFF3E3C6),
                  Color(0xFFFB894E),
                ],
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
              ),
              borderRadius: BorderRadius.circular(24.r),
            ),
            child: Text(
              'Go to Login',
              style: TextStyle(
                color: Colors.black,
                fontSize: 18.sp,
                fontFamily:
                    GoogleFonts.alexandria(
                      fontWeight: FontWeight.w600,
                    ).fontFamily,
                fontWeight: FontWeight.w600,
              ),
            ).center().inkWell(
              onTap: () async {
                await Navigator.of(context).push(
                  TransitionPageRoute(
                    builder: (context) => const UserAuthPage(),
                    transitionAnimation: RandomHexagonGridTransition(
                      colors: [
                        Color(0xFF83BE4A),
                        Color(0xFFF3E3C6),
                        Color(0xFFFB894E),
                      ],
                    ),
                  ),
                );
                // 不再需要手动setState，Redux状态变化会自动触发UI更新
              },
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildChatInterface(AppState state) {
    return Column(
      children: [
        // 标题
        Text(
          'CHAT LIST',
          style: TextStyle(
            color: Colors.white,
            fontSize: 16.sp,
            fontFamily:
                GoogleFonts.goblinOne(fontWeight: FontWeight.w400).fontFamily,
            fontWeight: FontWeight.bold,
            letterSpacing: 2.0,
          ),
        ).paddingTop(56.h).paddingBottom(20.h),

        // 主要内容区域
        Expanded(
          child: Container(
            margin: EdgeInsets.only(
              left: 16.w,
              right: 16.w,
              bottom: 110.h, // 底部导航栏上方
            ),
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.1),
              borderRadius: BorderRadius.circular(20.r),
              border: Border.all(
                color: Colors.white.withOpacity(0.2),
                width: 1,
              ),
            ),
            child: Row(
              children: [
                // 左侧联系人列表
                _buildContactList(state),

                // 右侧消息列表
                Expanded(child: _buildMessageList(state)),
              ],
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildContactList(AppState state) {
    final conversations = state.chatState.conversationCollection;
    // 按时间排序
    final sortedConversations = List<ChatConversationEntity>.from(
      conversations,
    );
    sortedConversations.sort(
      (a, b) => b.lastMessageTime.compareTo(a.lastMessageTime),
    );

    return Container(
      width: 63.w,
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.3),
        borderRadius: BorderRadius.all(Radius.circular(20.r)),
      ),
      child: Column(
        children: [
          // 联系人头像列表
          Expanded(
            child: ListView.builder(
              padding: EdgeInsets.symmetric(vertical: 16.h),
              itemCount: sortedConversations.length,
              itemBuilder: (context, index) {
                final conversation = sortedConversations[index];
                final isSelected =
                    _selectedConversationId == conversation.conversationId;

                return Padding(
                  padding: EdgeInsets.only(bottom: 16.h),
                  child: _buildContactAvatar(
                    conversation: conversation,
                    isSelected: isSelected,
                  ),
                );
              },
            ),
          ),

          // 添加按钮
          Container(
            width: 50.w,
            height: 50.w,
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.1),
              borderRadius: BorderRadius.circular(8.r),
              border: Border.all(
                color: Colors.white.withOpacity(0.3),
                width: 1,
                style: BorderStyle.solid,
              ),
            ),
            child: Icon(
              Icons.add,
              color: Colors.white.withOpacity(0.7),
              size: 24.w,
            ).center().inkWell(
              onTap: () {
                showVamosFollowUserDialog(context);
              },
            ),
          ).paddingBottom(16.h),
        ],
      ),
    );
  }

  Widget _buildContactAvatar({
    required ChatConversationEntity conversation,
    required bool isSelected,
  }) {
    return Container(
      width: 50.w,
      height: 50.w,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8.r),
        border: Border.all(
          color: isSelected ? const Color(0xFF83BE4A) : Colors.transparent,
          width: 2,
        ),
      ),
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          // 头像
          ClipRRect(
            borderRadius: BorderRadius.circular(8.r),
            child: Image.asset(
              conversation.participantAvatar,
              width: 48.w,
              height: 48.w,
              fit: BoxFit.cover,
            ),
          ),

          // 选中指示器
          if (isSelected)
            Positioned(
              top: 11.w,
              right: -8.w,
              bottom: 11.w,
              child: Container(
                width: 4.w,
                height: 30.w,
                decoration: const BoxDecoration(color: Color(0xFF83BE4A)),
              ),
            ),
        ],
      ),
    ).center().inkWell(
      onTap: () {
        _selectedConversationId = conversation.conversationId;
        chatManager.setActiveConversation(conversation.conversationId);
        setState(() {});
      },
    );
  }

  Widget _buildMessageList(AppState state) {
    if (_selectedConversationId == null) {
      return AnimatedSwitcher(
        duration: const Duration(milliseconds: 300),
        transitionBuilder: (Widget child, Animation<double> animation) {
          return FadeTransition(
            opacity: animation,
            child: SlideTransition(
              position: Tween<Offset>(
                begin: const Offset(0.3, 0.0),
                end: Offset.zero,
              ).animate(
                CurvedAnimation(parent: animation, curve: Curves.easeOutCubic),
              ),
              child: child,
            ),
          );
        },
        child: _buildEmptyState(),
      );
    }

    try {
      final conversation = state.chatState.conversationCollection.firstWhere(
        (conv) => conv.conversationId == _selectedConversationId,
      );

      return AnimatedSwitcher(
        duration: const Duration(milliseconds: 800),
        transitionBuilder: (Widget child, Animation<double> animation) {
          return FadeTransition(
            opacity: animation,
            child: SlideTransition(
              position: Tween<Offset>(
                begin: const Offset(0.2, 0.0),
                end: Offset.zero,
              ).animate(
                CurvedAnimation(parent: animation, curve: Curves.linear),
              ),
              child: child,
            ),
          );
        },
        child: Column(
          key: ValueKey(_selectedConversationId),
          children: [
            // 聊天头部
            _buildChatHeader(conversation),

            // 消息列表和输入框的容器
            Expanded(child: _buildMessagesList(conversation, state)),
          ],
        ),
      );
    } catch (e) {
      return AnimatedSwitcher(
        duration: const Duration(milliseconds: 300),
        transitionBuilder: (Widget child, Animation<double> animation) {
          return FadeTransition(
            opacity: animation,
            child: SlideTransition(
              position: Tween<Offset>(
                begin: const Offset(0.3, 0.0),
                end: Offset.zero,
              ).animate(
                CurvedAnimation(parent: animation, curve: Curves.easeOutCubic),
              ),
              child: child,
            ),
          );
        },
        child: _buildEmptyState(),
      );
    }
  }

  Widget _buildEmptyState() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Image.asset(
          'assets/images/no_data.png',
          width: 93.w,
          height: 85.w,
          fit: BoxFit.contain,
        ).paddingBottom(16.h),

        Text(
          'Select a contact to start chatting',
          style: TextStyle(
            color: Colors.white.withOpacity(0.7),
            fontSize: 16.sp,
            fontWeight: FontWeight.w500,
          ),
          textAlign: TextAlign.center,
        ),
      ],
    );
  }

  Widget _buildChatHeader(ChatConversationEntity conversation) {
    return AnimatedSwitcher(
      duration: const Duration(milliseconds: 300),
      transitionBuilder: (Widget child, Animation<double> animation) {
        return FadeTransition(
          opacity: animation,
          child: SlideTransition(
            position: Tween<Offset>(
              begin: const Offset(0.0, -0.3),
              end: Offset.zero,
            ).animate(
              CurvedAnimation(parent: animation, curve: Curves.easeOutCubic),
            ),
            child: child,
          ),
        );
      },
      child: Container(
        key: ValueKey('header_${conversation.conversationId}'),
        padding: EdgeInsets.only(
          left: 16.w,
          right: 16.w,
          top: 12.h,
          bottom: 0.h,
        ),
        child: Row(
          children: [
            // 联系人信息
            Expanded(
              child: Row(
                children: [
                  ClipOval(
                    child: Image.asset(
                      conversation.participantAvatar,
                      width: 32.w,
                      height: 32.w,
                      fit: BoxFit.cover,
                    ),
                  ).paddingRight(12.w),

                  Text(
                    conversation.participantName,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16.sp,
                      fontFamily:
                          GoogleFonts.notoSansSc(
                            fontWeight: FontWeight.w800,
                          ).fontFamily,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ],
              ),
            ),

            // 操作按钮
            Row(
              children: [
                Image.asset('assets/images/call.png', width: 24.w, height: 24.w)
                    .paddingRight(16.w)
                    .inkWell(
                      onTap: () {
                        _startVideoCall(conversation);
                      },
                    ),

                Image.asset(
                  'assets/images/report.png',
                  width: 24.w,
                  height: 24.w,
                ).inkWell(
                  onTap: () {
                    _showReportDialog(conversation);
                  },
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildMessagesList(
    ChatConversationEntity conversation,
    AppState state,
  ) {
    final messages = conversation.messageList;
    final currentUser = state.userState.activeUser;

    return Container(
      decoration: BoxDecoration(
        color: const Color(0xFFF6F6F6),
        borderRadius: BorderRadius.all(Radius.circular(6.r)),
      ),
      margin: EdgeInsets.symmetric(horizontal: 9.w, vertical: 9.h),
      child: Column(
        children: [
          // 消息列表
          Expanded(
            child:
                messages.isEmpty
                    ? Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Image.asset(
                            'assets/images/no_data.png',
                            width: 93.w,
                            height: 85.w,
                            fit: BoxFit.contain,
                          ),
                          Text(
                            'No messages yet',
                            style: TextStyle(
                              color: Colors.grey[600],
                              fontSize: 14.sp,
                            ),
                          ),
                        ],
                      ),
                    )
                    : ListView.builder(
                      padding: EdgeInsets.symmetric(
                        vertical: 16.h,
                        horizontal: 8.w,
                      ),
                      itemCount: messages.length,
                      itemBuilder: (context, index) {
                        final message = messages[index];
                        final isCurrentUser =
                            message.senderId == currentUser?.uniqueId;

                        return Padding(
                          padding: EdgeInsets.only(bottom: 12.h),
                          child: _buildMessageBubble(message, isCurrentUser),
                        );
                      },
                    ),
          ),

          // 输入框
          _buildMessageInput(conversation),
        ],
      ),
    );
  }

  Widget _buildMessageBubble(ChatMessageEntity message, bool isCurrentUser) {
    if (message.messageType == ChatMessageType.callFailedMessage) {
      return _buildCallFailedMessage();
    }

    return Row(
      mainAxisAlignment:
          isCurrentUser ? MainAxisAlignment.end : MainAxisAlignment.start,
      children: [
        Container(
          constraints: BoxConstraints(
            maxWidth: MediaQuery.of(context).size.width * (143 / 262),
          ),
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
          decoration: BoxDecoration(
            color: isCurrentUser ? Colors.white : const Color(0xFF83BE4A),
            borderRadius:
                isCurrentUser
                    ? BorderRadius.only(
                      topLeft: Radius.circular(10.r),
                      topRight: Radius.circular(10.r),
                      bottomLeft: Radius.circular(10.r),
                      bottomRight: Radius.circular(0.r),
                    )
                    : BorderRadius.only(
                      topLeft: Radius.circular(10.r),
                      topRight: Radius.circular(10.r),
                      bottomLeft: Radius.circular(0.r),
                      bottomRight: Radius.circular(10.r),
                    ),
            border:
                isCurrentUser
                    ? Border.all(color: Colors.grey.withOpacity(0.3), width: 1)
                    : null,
          ),
          child: Text(
            message.content,
            style: TextStyle(
              color: isCurrentUser ? Colors.black : Colors.white,
              fontSize: 12.sp,
              fontFamily:
                  GoogleFonts.notoSansSc(
                    fontWeight: FontWeight.w300,
                  ).fontFamily,
              fontWeight: FontWeight.w300,
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildCallFailedMessage() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
          decoration: BoxDecoration(
            color: Colors.red.withOpacity(0.1),
            borderRadius: BorderRadius.circular(16.r),
            border: Border.all(color: Colors.red.withOpacity(0.3), width: 1),
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                Icons.call_end,
                color: Colors.red,
                size: 16.w,
              ).paddingRight(8.w),

              Text(
                'Call failed',
                style: TextStyle(
                  color: Colors.red,
                  fontSize: 12.sp,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildMessageInput(ChatConversationEntity conversation) {
    final TextEditingController controller = TextEditingController();

    return Container(
      height: 60.h,
      padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
      decoration: BoxDecoration(
        color: const Color(0xFFEBEBEB),
        borderRadius: BorderRadius.all(Radius.circular(8.r)),
      ),
      child: Center(
        child: Container(
          height: 34.h,
          padding: EdgeInsets.symmetric(horizontal: 12.w),
          decoration: ShapeDecoration(
            color: Colors.white,
            shape: RoundedRectangleBorder(
              side: BorderSide(width: 1.w, color: const Color(0xFFBFBFBF)),
              borderRadius: BorderRadius.circular(4.r),
            ),
          ),
          child: Row(
            children: [
              Expanded(
                child: TextField(
                  controller: controller,
                  style: TextStyle(
                    color: Colors.black,
                    fontFamily:
                        GoogleFonts.notoSansSc(
                          fontWeight: FontWeight.w400,
                        ).fontFamily,
                    fontSize: 12.sp,
                  ),
                  decoration: InputDecoration(
                    hintText: 'Input Content',
                    hintStyle: TextStyle(
                      color: Colors.black.withValues(alpha: 0.25),
                      fontFamily:
                          GoogleFonts.notoSansSc(
                            fontWeight: FontWeight.w400,
                          ).fontFamily,
                      fontSize: 12.sp,
                    ),
                    border: InputBorder.none,
                    contentPadding: EdgeInsets.zero,
                    isDense: true,
                  ),
                  onSubmitted: (text) {
                    if (text.trim().isNotEmpty) {
                      _sendMessage(conversation, text.trim());
                      controller.clear();
                    }
                  },
                ),
              ),

              // 发送按钮
              Container(
                width: 20.w,
                height: 20.w,
                child: Image.asset(
                  'assets/images/send.png',
                  width: 20.w,
                  height: 20.w,
                ).inkWell(
                  onTap: () {
                    final text = controller.text.trim();
                    if (text.isNotEmpty) {
                      _sendMessage(conversation, text);
                      controller.clear();
                    }
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _sendMessage(ChatConversationEntity conversation, String content) {
    final currentUser = userManager.getCurrentUser();
    if (currentUser == null) return;

    chatManager.sendTextMessage(
      conversationId: conversation.conversationId,
      senderId: currentUser.uniqueId,
      receiverId: conversation.participantId,
      content: content,
    );
    // 不再需要手动setState，Redux状态变化会自动触发UI更新
  }

  /// 开始视频通话
  void _startVideoCall(ChatConversationEntity conversation) {
    Navigator.of(context).push(
      TransitionPageRoute(
        builder:
            (context) => VamosVideoCallInterface(
              conversationId: conversation.conversationId,
            ),
        transitionAnimation: GrowingBarsTransition(
          colors: [Color(0xFF83BE4A), Color(0xFFF3E3C6), Color(0xFFFB894E)],
        ),
      ),
    );
  }

  /// 显示举报对话框
  void _showReportDialog(ChatConversationEntity conversation) {
    showVamosReportDialog(
      context: context,
      title: 'Report User',
      subtitle: 'Please select a reason for reporting.',
      onReportSubmitted: (option) {
        _handleReportSubmission(conversation, option);
      },
    );
  }

  /// 处理举报提交
  void _handleReportSubmission(
    ChatConversationEntity conversation,
    VamosReportOption option,
  ) {
    // 显示举报成功提示
    ToastNotificationHelper.showSuccessToast(
      context,
      message: 'Report submitted successfully',
    );

    // 清除对话中的所有消息
    chatManager.clearConversationMessages(conversation.conversationId);
  }
}
